﻿using AutoMapper;
using MediatR;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.W.realize;
using MyMES.Read.API.Dtos;

namespace MyMES.Read.API.Application.CommendHandlers.W.realize
{
    public class GetBillingmanagementCommandHanders : IRequestHandler<GetBillingmanagementCommands, APIPaging<List<BilingmanagementDTO>>>
    {
        private readonly IBaseRepository<BilingmanagementDTO> repository;
        private readonly IMapper mapper;

        public GetBillingmanagementCommandHanders(IBaseRepository<BilingmanagementDTO> repository,IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 显示开票信息
        /// </summary>
        /// <param name="request">开票信息</param>
        /// <param name="cancellationToken">2025-4-14</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaging<List<BilingmanagementDTO>>> Handle(GetBillingmanagementCommands request, CancellationToken cancellationToken)
        {
            APIPaging<List<BilingmanagementDTO>> result = new APIPaging<List<BilingmanagementDTO>>();
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";
            var sql = "select a.bid,a.BillingNumber,a.BillingName,a.Billingtype,a.BillingTime,a.Collectticket,a.Invoicenumber,a.Remark,c.Invoiceamount from Billingmanagement a inner join BillingSales b on a.Bid=b.Bid inner join Salesordersheet c on b.SalesId=c.SalesId where a.IsDelete=false";

            var Bilingmanagement= repository.SelectAsync(sql).Result;
            var BillingSales = repository.SelectAsync(sql).Result;
            var Salesordersheet= repository.SelectAsync(sql).Result;

            var Biling = mapper.Map<List<BilingmanagementDTO>>(Bilingmanagement);
            var BillingSalesed = mapper.Map<List<BilingmanagementDTO>>(BillingSales);
            var Sales = mapper.Map<List<BilingmanagementDTO>>(Salesordersheet);

            foreach (var item in Biling)
            {
                item.SalesId = Sales.Where(x => x.SalesId == item.SalesId).FirstOrDefault().SalesId;
            }
            if (!string.IsNullOrEmpty(request.BillingNumber))
            {
                Biling = Biling.Where(x => x.BillingNumber.Contains(request.BillingNumber)).ToList();
            }

            result.TotalCount = Biling.Count;
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            Biling= Biling.Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            result.data = Biling;
            return result;

        }
    }
}
